<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Event;
use app\common\model\Product as ProductModel;
use think\Db;
use app\common\model\Customer as CustomerModel;
use app\common\model\Admin as AdminModel; // 假设 AdminModel 对应用户表
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date; // 用于处理 Excel 日期
use think\Request;
use app\common\service\UserPermissionService;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use app\common\model\User;

/**
 * 首页接口
 */
class Customer extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function getStatistics()
    {
        $userId = $this->auth->id;
        // 1. 全部

  
        $whereAll = ['is_delete' => 0, 'is_claim' => 1];
              //数据权限
        $userPermissionService = new UserPermissionService();
        $staffids=$userPermissionService->getUsersByPermission($this->auth->id);
        $whereAll['staff_id']=['in',$staffids];

        
        $totalAll = Db::name('customer')->where($whereAll)->count();
        // 2. 我负责的
        $whereMine = $whereAll;
        $whereMine['staff_id'] = $userId;
        $totalMine = Db::name('customer')->where($whereMine)->count();
        // 3. 下属负责的
        $staffids = Db::name('user')->where('leader_id', $userId)->column('id');
        $whereSub = $whereAll;
        if ($staffids) {
            $whereSub['staff_id'] = ['in', $staffids];
            $totalSub = Db::name('customer')->where($whereSub)->count();
        } else {
            $totalSub = 0;
        }
        // 4. 今日已跟进
        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayEnd = strtotime(date('Y-m-d 23:59:59'));
        $whereTodayFollow = $whereAll;
        $whereTodayFollow['lastfollowtime'] = ['between', [$todayStart, $todayEnd]];
        $totalTodayFollow = Db::name('customer')->where($whereTodayFollow)->count();
        // 5. 今日新增
        $todayStartStr = date('Y-m-d 00:00:00');
        $todayEndStr = date('Y-m-d 23:59:59');
        $whereTodayNew = $whereAll;
        $whereTodayNew['createtime'] = ['between', [$todayStartStr, $todayEndStr]];
        $totalTodayNew = Db::name('customer')->where($whereTodayNew)->count();
        // 6. 从未跟进的
        $whereNeverFollow = $whereAll;
        $whereNeverFollow['lastfollowtime'] = null;
        $totalNeverFollow = Db::name('customer')->where($whereNeverFollow)->count();
        // 7. 7天未跟进
        $sevenDaysAgo = strtotime('-7 days');
        $whereSevenDays = $whereAll;
        $whereSevenDays['lastfollowtime'] = ['<', $sevenDaysAgo];
        $totalSevenDays = Db::name('customer')->where($whereSevenDays)->count();
        $data = [
            ['type' => 1, 'title' => '全部', 'value' => $totalAll],
            ['type' => 2, 'title' => '我负责的', 'value' => $totalMine],
            ['type' => 3, 'title' => '下属负责的', 'value' => $totalSub],
            ['type' => 4, 'title' => '今日已跟进', 'value' => $totalTodayFollow],
            ['type' => 5, 'title' => '今日新增', 'value' => $totalTodayNew],
            ['type' => 6, 'title' => '从未跟进的', 'value' => $totalNeverFollow],
            ['type' => 7, 'title' => '7天未跟进', 'value' => $totalSevenDays],
        ];
        $this->success('success', $data);
    }

    /**
     * 首页
     *
     */
    public function getCustomerList()
    {
        $params = $this->request->post();
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);
        $type = $this->request->post('type', 1);
        $action = $this->request->post('action', 'list'); // 新增：action参数，list或export
        

        // 使用统一的buildWhere方法构建查询条件
        $where = $this->buildWhere($params, $type);
        $where['c.is_delete'] = 0;
        $where['c.is_claim'] = 1;


        // 如果是导出操作
        if ($action === 'export') {
            return $this->handleExport($where, $params);
        }
        if ($action === 'delete') {
            return $this->handleDelete($where, $params);
        }


        // 普通列表查询
        $total = Db::name('customer c')
            ->join('fa_user s', 'c.staff_id = s.id', 'left')
            ->join('fa_user us', 'c.user_id = us.id', 'left')
            ->field('c.*, s.name as staff_name,us.name as user_name')
            ->where($where)
            ->count();
        $list = Db::name('customer c')
            ->join('fa_user s', 'c.staff_id = s.id', 'left')
            ->join('fa_user us', 'c.user_id = us.id', 'left')
            ->field('c.*, s.name as staff_name,us.name as user_name')
            ->where($where)
            ->order('c.id', 'desc')
            ->page($page, $pageSize)
            ->select();

        $ids=Db::name('customer c')
        ->join('fa_user s', 'c.staff_id = s.id', 'left')
        ->join('fa_user us', 'c.user_id = us.id', 'left')
        ->field('c.*, s.name as staff_name,us.name as user_name')
        ->where($where)
        ->order('c.id', 'asc')
        ->column('c.id');
        $count=count($ids);
        $ids=implode(',',$ids);

     
        $request = \think\Request::instance();
        $domain = $request->domain();
        foreach ($list as $k => $v) {



            if (!empty($v['certificate']) && is_string($v['certificate'])) {
                $certificate = json_decode($v['certificate'], true);
                foreach ($certificate as $key => $value) {
                    $certificate[$key] = $domain . $value;
                }
                $list[$k]['certificate'] = $certificate;
            }
            
            // 计算今天和recieveDate之间的天数
            if (!empty($v['recieveDate'])) {
                $recieveDate = strtotime($v['recieveDate']);
                $today = strtotime(date('Y-m-d'));
                $daysDiff = ceil(($today - $recieveDate) / (24 * 60 * 60));

                if(!$daysDiff){
                    $daysDiff='';
                }else{
                    $daysDiff=$daysDiff.'天';
                }
                $list[$k]['days_since_recieve'] = $daysDiff;
                
            } else {
                $list[$k]['days_since_recieve'] = '';
            }


        }
        $this->success('请求成功', ['list' => $list, 'total' => $total,'idlist'=>$ids]);
    }


  


    private function handleDelete($where, $params)
    {
  
    
        // 使用与列表相同的关联查询获取 c.id 列表
        $ids = Db::name('customer c')
            ->join('fa_user s', 'c.staff_id = s.id', 'left')
            ->join('fa_user us', 'c.user_id = us.id', 'left')
            ->where($where)
            ->column('c.id');



        $find=Db::name('contracts')->where('customer_id','in',$ids)->where('is_delete',0)->find();
        if($find){
            $this->error('客户有合同，不能删除');
        }
            
        if (empty($ids)) {
            $this->success('共删除 0 条记录');
        }

        // 按ID更新，避免别名引起的歧义
        $result = Db::name('customer')
            ->where('id', 'in', $ids)
            ->update([
                'is_delete' => 1,
                'deletetime' => time(),
            ]);

        Db::commit();
        $deletedCount = $result ?: 0;
        $this->success("删除成功，共删除 {$deletedCount} 条记录");
    
    }

    //团队列表
    public  function getTeamList()
    {
        $customerId = $this->request->post('customerId', 'customerId');
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);
        $staff_id=CustomerModel::where('id',$customerId)->value('staff_id');
        $staffids= Db::name('customer_team')
            ->where(['customer_id' => $customerId])
            ->column('staff_id');
        array_push($staffids,$staff_id);
        $where=[];
        $where['u.id']=['in',$staffids];
        $where['u.is_delete']=0;
        // 普通列表查询
        $total = Db::name('user u')
            ->join('role r', 'u.role_id = r.id', 'LEFT')
            ->where($where)
            ->count();
        $list = Db::name('user u')
            ->join('role r', 'u.role_id = r.id', 'LEFT')
            ->field('u.*, r.name as role_name')
            ->where($where)
            ->page($page, $pageSize)
            ->select();
        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }

    public function getEventList()
    {

        // 获取分页参数
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);

        // 查询条件
        $where = [];
        $searchKey = $this->request->post('searchKey', '');
        if ($searchKey) {
            $where['title|customer_name'] = ['like', "%{$searchKey}%"];
        }

        $event = new Event();
        $total = $event->where($where)->count();
        $list = $event
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select();

        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }
    public function getProdcutList()
    {

        // 查询条件
        $where = [];
        $where['is_delete'] = 0;

        $product = new ProductModel();
        $total = $product->where($where)->count();
        $list = $product
            ->where($where)
            ->order('id', 'desc')
            ->select();

        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }
    public function getContactsList()
    {
        // 如果是 Selectpage 请求
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        // 获取分页参数
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);

        // 查询条件
        $where = [];
        $searchKey = $this->request->post('searchKey', '');
        if ($searchKey) {
            $where['name|customer_name|phone|manager'] = ['like', "%{$searchKey}%"];
        }

        $contacts = new \app\common\model\Contacts();
        $total = $contacts->where($where)->count();
        $list = $contacts
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select();

        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }
//    回款协议
    public function getPaymentRecordList()
    {
        // 如果是 Selectpage 请求
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        // 获取分页参数
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);

        // 查询条件
        $where = [];
        $searchKey = $this->request->post('searchKey', '');
        if ($searchKey) {
            $where['name|customer_name|phone|manager'] = ['like', "%{$searchKey}%"];
        }

        $paymentRecord = new \app\common\model\PaymentRecord();
        $total = $paymentRecord->where($where)->count();
        $list = $paymentRecord
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select();

        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }

    public function getWaterList()
    {
        // 如果是 Selectpage 请求
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        // 获取分页参数
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);

        // 查询条件
        $where = [];
        $searchKey = $this->request->post('searchKey', '');
        if ($searchKey) {
            $where['name|customer_name|phone|manager'] = ['like', "%{$searchKey}%"];
        }

        $water = new \app\common\model\Water();
        $total = $water->where($where)->count();
        $list = $water
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select();

        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }

    public function createCustomer()
    {

        $params = $this->request->post();

        // 参数验证
        if (empty($params)) {
            $this->error('参数不能为空');
        }


        // 处理沟通状态和起诉状态（将数组转为JSON字符串）
        if (isset($params['communicationStatus']) && is_array($params['communicationStatus'])) {
            $params['communicationStatus'] = implode(',', $params['communicationStatus']);
        }

        if (!empty($params['certificate']) && is_array($params['certificate'])) {

            $certificate = $params['certificate'];

            foreach ($certificate as $key => $value) {
                $certificate[$key] = removeDomainFromImageUrl($value);
            }
            $params['certificate'] = json_encode($certificate, JSON_UNESCAPED_UNICODE);
        }
        if (isset($params['lawsuitStatus']) && is_array($params['lawsuitStatus'])) {

            $params['lawsuitStatus'] = implode(',', $params['lawsuitStatus']);

        }

        // 处理部门ID（取数组最后一个值）
        if (isset($params['deptId']) && is_array($params['deptId'])) {
            $params['deptId'] = end($params['deptId']);
        }

        // 处理日期字段 - 将 ISO 8601 格式转换为 MySQL 格式
        $dateFields = ['compensationDate', 'filingTime', 'mailDate', 'paymentDate', 'courtTime', 'executionTime', 'recieveDate'];
        foreach ($dateFields as $field) {
            if (isset($params[$field]) && !empty($params[$field])) {
                $dateValue = $params[$field];
                
                // 处理 ISO 8601 格式 (如: 2025-08-12T16:00:00.000Z)
                if (is_string($dateValue) && strpos($dateValue, 'T') !== false) {
                    // 移除时区信息并转换为 MySQL 格式
                    $dateValue = str_replace(['T', 'Z'], ' ', $dateValue);
                    $dateValue = rtrim($dateValue, '.000');
                    $params[$field] = date('Y-m-d H:i:s', strtotime($dateValue));
                } else if (is_string($dateValue) && !empty($dateValue)) {
                    // 其他字符串格式的日期
                    $params[$field] = date('Y-m-d H:i:s', strtotime($dateValue));
                } else if (is_numeric($dateValue)) {
                    // 时间戳格式
                    $params[$field] = date('Y-m-d H:i:s', $dateValue);
                }
            } else {
                $params[$field] = null;
            }
        }

        // 处理金额字段
        $amountFields = ['backendAmount', 'loanAmount', 'repaidInterest', 'remainingPrincipal', 'remainingPenalty'];
        foreach ($amountFields as $field) {
            if (isset($params[$field])) {
                $params[$field] = floatval($params[$field]);
            }else{
                $params[$field] = null;
            }
        }
        unset($params['communicationStatus_text']);
        unset($params['lawsuitStatus_text']);
        unset($params['communication_status']);

    

        $CustomerModel = new CustomerModel();
        Db::startTrans();
        try {
            // 判断是新增还是修改
            if (isset($params['id']) && $params['id']) {
                // 修改 - 获取原始数据用于比较
                $originalData = $CustomerModel->where('id', $params['id'])->find();

                $result = $CustomerModel->where('id', $params['id'])->update($params);
                // 记录操作日志
                if ($result !== false) {

                    $changes = $this->getFieldChanges($originalData, $params);
                    if (!empty($changes)) {
                        $this->recordOperationLog($params['id'], $changes);
                    }
                }
            } else {
                // 新增
                
                $params['createtime']= $params['recieveDate'] = date('Y-m-d H:i:s');
                $params['staff_id']=$this->auth->id;
                $params['user_id']=$this->auth->id;
                $result = $CustomerModel->insert($params);
            }
            Db::commit();

            if ($result !== false) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取字段变化并生成操作描述
     * @param array $originalData 原始数据
     * @param array $newData 新数据
     * @return string 操作描述
     */
    private function getFieldChanges($originalData, $newData)
    {
        $changes = [];
        
        // 字段映射表，用于生成中文描述
        $fieldMap = [
            'customerName' => '客户名称',
            'productName' => '产品名称',
            'uidipin' => 'UID/PIN',
            'batch' => '批次',
            'orderNo' => '订单号码',
            'orgName' => '机构名称',
            'guaranteeCompany' => '担保公司',
            'phone' => '电话号码',
            'phone1' => '电话号码1',
            'emergencyPhone' => '紧急联系人电话',
            'idCard' => '身份证件号码',
            'homeAddress' => '家庭地址',
            'communicationStatus' => '沟通状态',
            'lawsuitStatus' => '起诉状态',
            'deptId' => '归属部门',
            'backendAmount' => '后台金额',
            'loanAmount' => '借款金额',
            'repaidInterest' => '已还利息',
            'remainingPrincipal' => '剩余本金',
            'remainingPenalty' => '剩余罚息',
            'compensationDate' => '代偿日期',
            'plaintiff' => '原告主体',
            'filingTime' => '立案时间',
            'mailNo' => '邮寄单号',
            'mailDate' => '邮寄日期',
            'paymentDate' => '缴费时间',
            'judgeName' => '法官姓名',
            'courtPhone' => '法官电话',
            'filingCaseNo' => '立案案号',
            'courtTime' => '开庭时间',
            'verdictResult' => '调解/判决结果',
            'executionCaseNo' => '执行案号',
            'executionTime' => '执行时间',
            'remark' => '备注信息',
            'lastfollowcon' => '最新跟进内容',
            'lawyer' => '负责律师',
            'courtAddress' => '法院地址',
            'court' => '立案法院',
            'revieveTime' => '领取时间',
            'staff_id' => '负责人',
            'certificate' => '立案凭证',
            'compensationAmount' => '代偿金额',
            'repaidAmount' => '已还本金',
            'repaidPenalty' => '已还罚息',
            'remainingInterest' => '剩余利息',
            'verdict' => '判决结果',
            'recieveDate' => '上传/邮寄日期'
        ];
        
        // 需要忽略的字段
        $ignoreFields = ['updatetime', 'createtime', 'user_id', 'is_claim', 'claimtime', 'is_delete', 'deletetime'];
        
        foreach ($newData as $field => $newValue) {
            // 跳过忽略的字段
            if (in_array($field, $ignoreFields)) {
                continue;
            }
            
            // 获取原始值
            $originalValue = isset($originalData[$field]) ? $originalData[$field] : '';
            
            // 处理空值比较
            if (empty($originalValue) && empty($newValue)) {
                continue;
            }
            
            // 处理数值类型字段
            if (in_array($field, ['backendAmount', 'loanAmount', 'repaidInterest', 'remainingPrincipal', 'remainingPenalty', 'compensationAmount', 'repaidAmount', 'repaidPenalty', 'remainingInterest'])) {
                $originalValue = floatval($originalValue);
                $newValue = floatval($newValue);
                if ($originalValue == $newValue) {
                    continue;
                }
            }
            
            // 处理日期字段
            if (in_array($field, ['compensationDate', 'filingTime', 'mailDate', 'paymentDate', 'courtTime', 'executionTime', 'revieveTime'])) {
                $originalValue = $originalValue ? date('Y-m-d', strtotime($originalValue)) : '';
                $newValue = $newValue ? date('Y-m-d', strtotime($newValue)) : '';
                if ($originalValue == $newValue) {
                    continue;
                }
            }
            
            // 处理负责人字段
            if ($field === 'staff_id' && !empty($newValue)) {
                $staffName = Db::name('user')->where('id', $newValue)->value('name');
                $newValue = $staffName ?: $newValue;
                if (isset($originalData['staff_id']) && !empty($originalData['staff_id'])) {
                    $originalStaffName = Db::name('user')->where('id', $originalData['staff_id'])->value('name');
                    $originalValue = $originalStaffName ?: $originalData['staff_id'];
                }
            }
            
            // 处理部门字段
            if ($field === 'deptId' && !empty($newValue)) {
                $deptName = Db::name('department')->where('id', $newValue)->value('name');
                $newValue = $deptName ?: $newValue;
                if (isset($originalData['department_id']) && !empty($originalData['department_id'])) {
                    $originalDeptName = Db::name('department')->where('id', $originalData['department_id'])->value('name');
                    $originalValue = $originalDeptName ?: $originalData['department_id'];
                }
            }
            
            // 比较值是否发生变化
            if ($originalValue != $newValue) {
                $fieldName = isset($fieldMap[$field]) ? $fieldMap[$field] : $field;
                $originalValue = $originalValue ?: '空';
                $newValue = $newValue ?: '空';
                $changes[] = "将{$fieldName}修改为：{$newValue}";
            }
        }
        
        return implode('；', $changes);
    }

    /**
     * 记录操作日志
     * @param int $customerId 客户ID
     * @param string $content 操作内容
     */
    private function recordOperationLog($customerId, $content)
    {
        $logData = [
            'customer_id' => $customerId,
            'user_id' => $this->auth->id,
            'content' => $content,
            'createtime' => date('Y-m-d H:i:s'),
            'ip' => $this->request->ip(),
        ];
        
        Db::name('operation_log')->insert($logData);
    }

    public function getCustomerDetail()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数错误');
        }

        try {
            $customer = CustomerModel::where('id', $id)->find();
            if (!$customer) {
                return json(['code' => 0, 'msg' => '客户不存在', 'data' => null]);
            }
            $customer->communication_status=$customer->communicationStatus;
            // 处理 JSON 字段
            $communicationStatus = explode(',', $customer->communicationStatus);
            $customer->communicationStatus = array_filter($communicationStatus);

            $lawsuitStatus = explode(',', $customer->lawsuitStatus);
            $customer->lawsuitStatus = array_filter($lawsuitStatus);

            $request = \think\Request::instance();
            $domain = $request->domain();

            if (!empty($customer->certificate)) {
                $certificate = json_decode($customer->certificate, true);
                foreach ($certificate as $key => $value) {
                    $certificate[$key] = $domain . $value;
                }
                $customer->certificate = $certificate;
            }


            $this->success('获取成功', $customer);
        } catch (Exception $e) {
            $this->error('暂无该数据');
        }
    }
    public function getCustomerInfo_old()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数错误');
        }

        try {
            $customer = CustomerModel::where('id', $id)->find();
            if (!$customer) {
                return json(['code' => 0, 'msg' => '客户不存在', 'data' => null]);
            }
            $customer->communication_status=$customer->communicationStatus;
            // 处理 JSON 字段
            $communicationStatus = explode(',', $customer->communicationStatus);
            $customer->communicationStatus = array_filter($communicationStatus);

            $lawsuitStatus = explode(',', $customer->lawsuitStatus);
            $customer->lawsuitStatus = array_filter($lawsuitStatus);

            $request = \think\Request::instance();
            $domain = $request->domain();

            if (!empty($customer->certificate)) {
                $certificate = json_decode($customer->certificate, true);
                foreach ($certificate as $key => $value) {
                    $certificate[$key] = $domain . $value;
                }
                $customer->certificate = $certificate;
            }

            if($customer->user_id){
                $user=\app\admin\model\User::where('id',$customer->user_id)->field('name')->find();
                $customer->user=$user;
            }
            if($customer->staff_id){
                $staff=\app\admin\model\User::where('id',$customer->staff_id)->field('name')->find();
                $customer->staff=$staff;
            }
            $followCount=\app\common\model\Follow::where('customer_id',$id)->where('is_delete',0)->count();
            $customer->followCount=$followCount??0;

            // 1. 合同总金额
            $contracts = \think\Db::name('contracts')
                ->where(['customer_id' => $id, 'is_delete' => 0])
                ->field('id,amount')
                ->select();
            $contract_total_amount = 0;
            $contract_ids = [];
            foreach ($contracts as $c) {
                $contract_total_amount += floatval($c['amount']);
                $contract_ids[] = $c['id'];
            }

            // 2. 回款总金额
            $payment_total_amount = 0;
            if (!empty($contract_ids)) {
                $payment_total_amount = \think\Db::name('payment_record')
                    ->where(['is_delete' => 0])
                    ->where('contract_id', 'in', $contract_ids)
                    ->sum('amount');
                $payment_total_amount = floatval($payment_total_amount);
            }

            $customer->salesAmount=$contract_total_amount??0;
            $customer->repaidAmount=$payment_total_amount??0;
            $customer->unrepaidAmount=($contract_total_amount - $payment_total_amount)??0;

            $this->success('获取成功', $customer);
        } catch (Exception $e) {
            $this->error('暂无该数据');
        }
    }


    public function getCustomerInfo()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数错误');
        }

        try {
            $customer = Db::name('customer')->where('id', $id)->find();
            if (!$customer) {
                return json(['code' => 0, 'msg' => '客户不存在', 'data' => null]);
            }
            $customer['communication_status']=$customer['communicationStatus'];
            // 处理 JSON 字段
            $communicationStatus = explode(',', $customer['communicationStatus']);
            $customer['communicationStatus'] = array_filter($communicationStatus);

            $lawsuitStatus = explode(',', $customer['lawsuitStatus']);
            $customer['lawsuitStatus'] = array_filter($lawsuitStatus);

            $request = \think\Request::instance();
            $domain = $request->domain();

            if (!empty($customer->certificate)) {
                $certificate = json_decode($customer['certificate'], true);
                foreach ($certificate as $key => $value) {
                    $certificate[$key] = $domain . $value;
                }
                $customer['certificate'] = $certificate;
            }

            if($customer['user_id']){
                $user=\app\admin\model\User::where('id',$customer['user_id'])->field('name')->find();
                $customer['user']=$user;
            }
            if($customer['staff_id']){
                $staff=\app\admin\model\User::where('id',$customer['staff_id'])->field('name')->find();
                $customer['staff']=$staff;
            }
            $followCount=\app\common\model\Follow::where('customer_id',$id)->where('is_delete',0)->count();
            $customer['followCount']=$followCount??0;

            // 1. 合同总金额
            $contracts = \think\Db::name('contracts')
                ->where(['customer_id' => $id, 'is_delete' => 0])
                ->field('id,amount')
                ->select();
            $contract_total_amount = 0;
            $contract_ids = [];
            foreach ($contracts as $c) {
                $contract_total_amount += floatval($c['amount']);
                $contract_ids[] = $c['id'];
            }

            // 2. 回款总金额
            $payment_total_amount = 0;
            if (!empty($contract_ids)) {
                $payment_total_amount = \think\Db::name('payment_record')
                    ->where(['is_delete' => 0])
                    ->where('contract_id', 'in', $contract_ids)
                    ->sum('amount');
                $payment_total_amount = floatval($payment_total_amount);
            }

            $customer['salesAmount']=$contract_total_amount??0;
            $customer['repaidAmount']=$payment_total_amount??0;
            $customer['unrepaidAmount']=($contract_total_amount - $payment_total_amount)??0;

            $this->success('获取成功', $customer);
        } catch (Exception $e) {
            $this->error('暂无该数据');
        }
    }
    
    
    public function staffInfo(){
        $id=$this->auth->id;
        $staff=\app\admin\model\User::where('id',$id)->field('id,name')->find();
        $this->success('获取成功',$staff);
    }

    public function deleteCustomer()
    {

        $ids = $this->request->post('ids', '');
        $ids = explode(',', $ids);
        $customer = new \app\common\model\Customer();

        $find=Db::name('contracts')->where('customer_id','in',$ids)->where('is_delete',0)->find();
        if($find){
            $this->error('客户有合同，不能删除');
        }

        $customer->whereIn('id', $ids)->update(['deletetime' =>time(),'is_delete'=>1]);
        $this->success();

    }

    /**
     * 处理客户导入
     */
    public function processCustomerImport_old()
    {
        $fileUrl = $this->request->post('fileUrl');
        $sheetName = $this->request->post('sheetName');
        $responsiblePersonType = $this->request->post('responsiblePersonType', 'assign');
        $responsibleUserId = $this->request->post('responsibleUserId', null);
        $dataConflictPolicy = $this->request->post('dataConflictPolicy', 'skip');
        $overwriteField = $this->request->post('overwriteField', '');

        if (empty($fileUrl) || empty($sheetName)) {
            $this->error('文件URL和Sheet名称不能为空');
        }

        // FastAdmin 的文件存储通常在 public/uploads/
        // 这里假设 $fileUrl 是从 FastAdmin 的上传接口返回的相对路径，例如 /uploads/20250617/xxx.xls
        $localFilePath = ROOT_PATH . 'public' . str_replace('/', DS, $fileUrl);


        if (!file_exists($localFilePath)) {
            $this->error('服务器上找不到文件，请确认文件已正确上传路径：' . $localFilePath);
        }


        $success = $error = 0;
        $importedCount = 0;
        $updatedCount = 0;
        $skippedCount = 0;
        $failedCount = 0;


        $errorMessages = [];
        $customerModel = new CustomerModel();


        $spreadsheet = IOFactory::load($localFilePath);
        $sheet = $spreadsheet->getSheetByName($sheetName);

        if (!$sheet) {
            $this->error('指定的Sheet名称不存在：' . $sheetName);
        }

        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn(); // 比如 'BO'
        $maxColIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);


        $header = [];
        for ($i = 1; $i <= $maxColIndex; $i++) {
            $header[] = trim($sheet->getCellByColumnAndRow($i, 1)->getValue());
        }


        // 定义 Excel 表头到数据库字段的映射 (根据 exportExcel 的 fieldMap )
        $excelToDbMap = [
            '客户名称' => 'customerName',
            '产品名称/类别' => 'productName',
            '批次' => 'batch',
            '订单号码' => 'orderNo',
            '机构名称' => 'orgName',
            'UID/PIN' => 'uidipin',
            '负责人' => 'staff_id',
            '电话号码' => 'phone',
            '沟通状态' => 'communicationStatus',
            '邮箱状态' => 'emailStatus',
            '代言金额' => 'amount',
            '最新跟进内容' => 'lastfollowcon',
            '负责律师' => 'lawyer',
            '立案案号' => 'filingCaseNo',
            '执行案号' => 'executionCaseNo',
            '立案法院' => 'court',
            '法院电话' => 'courtPhone',
            '立案时间' => 'filingTime',
            '邮寄日期' => 'mailDate',
            '领取日期' => 'recieveDate',
            '更新日期' => 'updatetime',
            '担保公司' => 'guaranteeCompany',
            '电话号码1' => 'phone1',
            '紧急联系人/其他联系人电话' => 'emergencyPhone',
            '身份证件号码' => 'idCard',
            '家庭地址' => 'homeAddress',
            '起诉状态' => 'lawsuitStatus',
            '归属部门' => 'deptId',
            '后台金额' => 'backendAmount',
            '借款金额/本金' => 'loanAmount',
            '已还利息' => 'repaidInterest',
            '剩余本金' => 'remainingPrincipal',
            '剩余罚息' => 'remainingPenalty',
            '代偿日期' => 'compensationDate',
            '原告主体' => 'plaintiff',
            '邮寄单号' => 'mailNo',
            '缴费时间' => 'paymentDate',
            '法官姓名' => 'judgeName',
            '法官电话' => 'courtPhone',
            '开庭时间' => 'courtTime',
            '调解/判决结果' => 'verdictResult',
            '执行时间' => 'executionTime',
            '备注信息' => 'remark',
            '最后跟进日期' => 'lastfollowtime', // 注意：前端是 lastfollowcon，这里是 lastfollowtime
            '创建时间' => 'createtime',
        ];

        // 缓存用户名称到ID的映射，避免循环查询
        $userCache = [];

        for ($rowNum = 2; $rowNum <= $highestRow; $rowNum++) { // 从第二行开始读取数据
            $rowData = [];
            $rowError = [];

            for ($i = 1; $i <= $maxColIndex; $i++) {
                $headerIndex = $i - 1;

                if (!isset($header[$headerIndex])) {
                    continue;
                }

                $headerName = $header[$headerIndex];
                $cellValue = $sheet->getCellByColumnAndRow($i, $rowNum)->getValue();

                if (isset($excelToDbMap[$headerName])) {
                    $dbField = $excelToDbMap[$headerName];
                    $rowData[$dbField] = $cellValue;
                }
            }


            if (empty($rowData) || !array_filter($rowData)) { // 跳过空行
                continue;
            }

            $customerData = [];
            foreach ($rowData as $key => $value) {
                $value = trim($value);

                // 根据 createCustomer 方法的逻辑处理字段
                switch ($key) {
                    case 'communicationStatus':
                    case 'lawsuitStatus':
                        // 假设 Excel 里的沟通状态和起诉状态是逗号分隔的字符串
                        $customerData[$key] = json_encode(explode(',', $value), JSON_UNESCAPED_UNICODE);
                        break;
                    case 'compensationDate':
                    case 'uidipin':
                        if ($value) {
                            $customerData[$key] = $value;
                        }
                        break;
                    case 'filingTime':
                    case 'mailDate':
                    case 'paymentDate':
                    case 'courtTime':
                    case 'executionTime':
                    case 'createtime':
                    case 'updatetime':
                    case 'recieveDate':
                    case 'lastfollowtime':
                        // PHPSpreadsheet date handling: convert Excel numeric date to Unix timestamp
                        if (is_numeric($value) && $value > 0) {
                            $customerData[$key] = Date::excelToTimestamp($value);
                        } else if (is_string($value) && !empty($value)) {
                            $customerData[$key] = strtotime($value);
                        } else {
                            $customerData[$key] = null; // 或者设置为0，根据数据库字段类型决定
                        }
                        break;
                    case 'backendAmount':
                    case 'loanAmount':
                    case 'repaidInterest':
                    case 'remainingPrincipal':
                    case 'remainingPenalty':
                    case 'amount':
                        $customerData[$key] = floatval($value);
                        break;
                    case 'staff_id': // 负责人姓名（如果从Excel导入）
                        if ($responsiblePersonType === 'excel') {
                            $user = Db::name('user')->where('name', $value)->find();
                            if ($user) {
                                $staff_id = $user['id'];
                                $customerData[$key] = $staff_id;
                            }
                        }
                        break;
                    default:
                        $customerData[$key] = $value;
                        break;
                }
            }


            // 处理指定负责人类型
            if ($responsiblePersonType === 'assign' && $responsibleUserId !== null) {
                // 假设客户表有 manager_id 字段存储用户ID，manager 字段存储用户姓名
                $customerData['staff_id'] = $responsibleUserId;
            }

            $customerData['is_claim'] = 1;


            if (empty($customerData['customerName'])) {
                continue;
            }
//重复规则去掉start
            // 查找现有客户
            $existingCustomer = null;
            $lookupField = $overwriteField;

            if ($dataConflictPolicy !== 'allow') { // 如果不是允许重复，才进行查找
                if ($lookupField === '全部') {
                    // '全部'覆盖策略要求 Excel 中有 'id' 字段作为主键
                    if (isset($customerData['id']) && !empty($customerData['id'])) {
                        $existingCustomer = CustomerModel::where('id', $customerData['id'])->find();
                    } else {
                        $rowError[] = "选择'全部'覆盖策略时，Excel中缺少客户ID字段，无法定位记录。";
                        $skippedCount++;
                        $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                        continue;
                    }
                } elseif (!empty($lookupField) && isset($customerData[$lookupField]) && !empty($customerData[$lookupField])) {
                    $existingCustomer = CustomerModel::where($lookupField, $customerData[$lookupField])->find();
                }
            }

            if ($existingCustomer) {
                if ($dataConflictPolicy === 'skip') {
                    $skippedCount++;
                    $rowError[] = "客户已存在（{$lookupField}: {$customerData[$lookupField]}），跳过。";
                    $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                    continue;
                } elseif ($dataConflictPolicy === 'overwrite') {
                    // 更新现有客户
                    $res = $existingCustomer->save($customerData);
                    if ($res !== false) {
                        $updatedCount++;
                    } else {
                        $failedCount++;
                        $rowError[] = "更新失败（" . ($existingCustomer->getError() ?: '未知错误') . "）。";
                        $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                    }
                }
            } else {
                $newCustomer = new CustomerModel();
                $customerData['createtime'] = date('Y-m-d H:i:s');

                $res = $newCustomer->save($customerData);
                if ($res !== false) {
                    $importedCount++;
                } else {
                    $failedCount++;
                    $rowError[] = "插入失败（" . ($newCustomer->getError() ?: '未知错误') . "）。";
                    $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                }

            }
        }

//重复规则去掉end

        $newCustomer = new CustomerModel();
        $customerData['createtime'] = date('Y-m-d H:i:s');

        $res = $newCustomer->save($customerData);
        if ($res !== false) {
            $importedCount++;
        } else {
            $failedCount++;
            $rowError[] = "插入失败（" . ($newCustomer->getError() ?: '未知错误') . "）。";
            $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
        }






        Db::name('import_log')->insert(
            [
                'success' => $importedCount,
                'fail' => $failedCount,
                'url' => $fileUrl,
                'name' => $sheetName,
                'type' => 1,
                'total' => $importedCount + $failedCount,
                'user_id' => $this->auth->id,
                'createtime' => date('Y-m-d H:i:s'),
            ]
        );

        $this->success('导入完成', [
            'imported' => $importedCount,
            'updated' => $updatedCount,
            'skipped' => $skippedCount,
            'failed' => $failedCount,
            'errors' => $errorMessages,
            'total_rows' => $highestRow - 1, // 总行数（减去表头）
            'processed_rows' => $importedCount + $updatedCount + $skippedCount + $failedCount, // 处理的行数
            'batch_size' => 1000, // 批次大小
            'performance' => [
                'total_time' => microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'],
                'rows_per_second' => ($importedCount + $updatedCount) / max(1, microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'])
            ]
        ]);

    }


    public function processCustomerImport()
    {
        $fileUrl = $this->request->post('fileUrl');
        $sheetName = $this->request->post('sheetName');
        $responsiblePersonType = $this->request->post('responsiblePersonType', 'assign');
        $responsibleUserId = $this->request->post('responsibleUserId', null);
        $dataConflictPolicy = $this->request->post('dataConflictPolicy', 'skip');
        $overwriteField = $this->request->post('overwriteField', '');
        $fieldMappings = $this->request->post('fieldMappings/a', []); // 前端传的映射关系

        if (empty($fileUrl) || empty($sheetName) || empty($fieldMappings)) {
            $this->error('文件URL、Sheet名称和字段映射不能为空');
        }

        $localFilePath = ROOT_PATH . 'public' . str_replace('/', DS, $fileUrl);
        if (!file_exists($localFilePath)) {
            $this->error('服务器上找不到文件，请确认文件已正确上传路径：' . $localFilePath);
        }

        $importedCount = 0;
        $updatedCount = 0;
        $skippedCount = 0;
        $failedCount = 0;
        $errorMessages = [];

        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($localFilePath);
        $sheet = $spreadsheet->getSheetByName($sheetName);
        if (!$sheet) {
            $this->error('指定的Sheet名称不存在：' . $sheetName);
        }

        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        $maxColIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

        // 1. 生成 Excel列名 => 列号 的映射
        $excelHeaderMap = [];
        for ($i = 1; $i <= $maxColIndex; $i++) {
            $headerName = trim($sheet->getCellByColumnAndRow($i, 1)->getValue());
            if ($headerName !== '') {
                $excelHeaderMap[$headerName] = $i;
            }
        }

        // 2. 生成 系统字段 => [excel列名, 默认值, 列号] 的映射
        $fieldMap = [];
        foreach ($fieldMappings as $map) {
            $sysField = $map['systemField'];
            $excelField = $map['excelField'];
            $defaultValue = $map['defaultValue'];
            $colIndex = isset($excelHeaderMap[$excelField]) ? $excelHeaderMap[$excelField] : null;
            $fieldMap[$sysField] = [
                'excelField' => $excelField,
                'defaultValue' => $defaultValue,
                'colIndex' => $colIndex
            ];
        }


        $allData = [];

        // 开启事务
        Db::startTrans();
        try {
            // 禁用自动提交以提高性能
            Db::execute('SET autocommit = 0');
        for ($rowNum = 2; $rowNum <= $highestRow; $rowNum++) { // 从第二行开始
            $rowData = [];
            $rowError = [];

            // 3. 按系统字段组装数据
            foreach ($fieldMap as $sysField => $info) {


                $value = '';
                if ($info['colIndex']) {
                    $cellValue = $sheet->getCellByColumnAndRow($info['colIndex'], $rowNum)->getValue();
                    $value = trim($cellValue);
                }
                if ($value === '' && $info['defaultValue'] !== '') {
                    $value = $info['defaultValue'];
                }

                // 特殊处理日期/时间字段
                if (in_array($sysField, ['compensationDate', 'filingTime', 'mailDate', 'paymentDate', 'courtTime', 'executionTime', 'revieveTime', 'createtime', 'updatetime', 'lastfollowtime'])) {
                    if ($value === '' || $value === null) {
                        $value = null; // 空值设为 null
                    } else {
                        // 根据字段类型分别处理
                        switch ($sysField) {
                            case 'filingTime':
                            case 'mailDate':
                            case 'paymentDate':
                            case 'courtTime':
                            case 'executionTime':
                                // date 类型，转换为 Y-m-d 格式
                                if (is_numeric($value)) {
                                    $value = date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value));
                                } else {
                                    $timestamp = strtotime($value);
                                    $value = $timestamp ? date('Y-m-d', $timestamp) : null;
                                }
                                break;

                            case 'createtime':
                            case 'revieveTime':
                                // datetime 类型，转换为 Y-m-d H:i:s 格式
                                if (is_numeric($value)) {
                                    $value = date('Y-m-d H:i:s', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value));
                                } else {
                                    $timestamp = strtotime($value);
                                    $value = $timestamp ? date('Y-m-d H:i:s', $timestamp) : null;
                                }
                                break;

                            case 'compensationDate':
                                    // timestamp 类型，转换为 datetime 格式
                                if (is_numeric($value)) {
                                        $timestamp = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value);
                                        $value = $timestamp ? date('Y-m-d H:i:s', $timestamp) : null;
                                } else {
                                    $timestamp = strtotime($value);
                                        $value = $timestamp ? date('Y-m-d H:i:s', $timestamp) : null;
                                }
                                break;

                            case 'lastfollowtime':
                            case 'updatetime':
                                // int 类型，转换为时间戳
                                if (is_numeric($value)) {
                                    $value = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value);
                                } else {
                                    $timestamp = strtotime($value);
                                    $value = $timestamp ? $timestamp : null;
                                }
                                break;
                        }
                    }
                }

                    // 特殊处理金额字段
                    if (in_array($sysField, ['backendAmount', 'loanAmount', 'repaidInterest', 'remainingPrincipal', 'remainingPenalty', 'compensationAmount', 'repaidAmount', 'repaidPenalty', 'remainingInterest', 'invoiceAmount'])) {
                        if ($value === '' || $value === null || $value === '0' || $value === 0) {
                            $value = null; // 空值或0设为 null
                        } else {
                            $value = floatval($value);
                            if ($value == 0) {
                                $value = null; // 如果转换后为0，也设为null
                            }
                        }
                    }

                $rowData[$sysField] = $value;
            }




            if (empty($rowData) || !array_filter($rowData)) {
                    $skippedCount++;
                    $rowError[] = "该行为空行，已跳过。";
                    $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                continue;
            }

            // 4. 处理负责人
            if ($responsiblePersonType === 'assign' && $responsibleUserId !== null) {
                $rowData['staff_id'] = $responsibleUserId;
            } elseif ($responsiblePersonType === 'excel' && isset($rowData['staff_id'])) {
                $user = Db::name('user')->where('name', $rowData['staff_id'])->where('is_delete',0)->find();
                if ($user) {
                    $rowData['staff_id'] = $user['id'];
                } else {
                    $failedCount++;
                        $rowError[] = "负责人 '{$rowData['staff_id']}' 不存在或已被删除。";
                        $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                    continue;
                }
            }

            $rowData['is_claim'] = 1;
            //创建人
            $rowData['user_id'] = $this->auth->id;

                // 验证必填字段
            if (empty($rowData['customerName'])) {
                $failedCount++;
                    $rowError[] = "客户名称不能为空。";
                    $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                continue;
            }

                // 验证手机号格式（如果提供了手机号）
                // if (!empty($rowData['phone']) && !preg_match('/^1[3-9]\d{9}$/', $rowData['phone'])) {
                //     $failedCount++;
                //     $rowError[] = "手机号格式不正确：{$rowData['phone']}。";
                //     $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                //     continue;
                // }

                // 验证身份证号格式（如果提供了身份证号）
                // if (!empty($rowData['idCard']) && !preg_match('/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/', $rowData['idCard'])) {
                //     $failedCount++;
                //     $rowError[] = "身份证号格式不正确：{$rowData['idCard']}。";
                //     $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                //     continue;
                // }

            // 5. 查找现有客户
            $existingCustomer = null;
            $lookupField = $overwriteField;

            //关闭跳过功能
            $dataConflictPolicy='allow';//仅仅加上这一行



            if ($dataConflictPolicy !== 'allow') {
                if ($lookupField === '全部') {
                    if (isset($rowData['id']) && !empty($rowData['id'])) {
                        $existingCustomer = CustomerModel::where('id', $rowData['id'])->find();
                    } else {
                        $rowError[] = "选择'全部'覆盖策略时，Excel中缺少客户ID字段，无法定位记录。";
                        $skippedCount++;
                        $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                        continue;
                    }
                } elseif (!empty($lookupField) && isset($rowData[$lookupField]) && !empty($rowData[$lookupField])) {
                    $existingCustomer = CustomerModel::where($lookupField, $rowData[$lookupField])->find();
                }
            }


            if ($existingCustomer) {
                if ($dataConflictPolicy === 'skip') {
                    $skippedCount++;
                    $rowError[] = "客户已存在（{$lookupField}: {$rowData[$lookupField]}），跳过。";
                    $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                    continue;
                } elseif ($dataConflictPolicy === 'overwrite') {
                        try {
                    $res = $existingCustomer->save($rowData);
                    if ($res !== false) {
                        $updatedCount++;
                    } else {
                        $failedCount++;
                                $errorMsg = $existingCustomer->getError();
                                if (empty($errorMsg)) {
                                    $errorMsg = '数据库更新失败，请检查数据格式是否正确。';
                                }
                                $rowError[] = "更新失败：{$errorMsg}";
                                $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                            }
                        } catch (\Exception $e) {
                            $failedCount++;
                            $rowError[] = "更新失败：{$e->getMessage()}";
                        $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                    }
                }
            } else {
                    try {
                        $rowData['createtime'] = date('Y-m-d H:i:s');
                        $rowData['recieveDate'] = date('Y-m-d H:i:s');
                    } catch (\Exception $e) {
                    $failedCount++;
                        $rowError[] = "插入失败：{$e->getMessage()}";
                    $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
                }
            }

                $allData[] = $rowData;
            }



            // 一次性插入所有数据
            if (!empty($allData)) {
                try {
                    $res = Db::name('customer')->insertAll($allData);
                    if ($res !== false) {
                        $importedCount = count($allData);
                    } else {
                        $failedCount = count($allData);
                        $errorMessages[] = "批量插入失败：数据库操作失败";
                    }
                } catch (\Exception $e) {
                    $failedCount = count($allData);
                    $errorMessages[] = "批量插入失败：{$e->getMessage()}";
                }
            }



            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $failedCount = $highestRow - 1; // 所有数据都失败
            $errorMessages[] = "导入过程中发生错误：{$e->getMessage()}";
        }

        Db::name('import_log')->insert([
            'success' => $importedCount,
            'fail' => $failedCount,
            'url' => $fileUrl,
            'name' => $sheetName,
            'type' => 1,
            'total' => $importedCount + $failedCount,
            'user_id' => $this->auth->id,
            'createtime' => date('Y-m-d H:i:s'),
        ]);

        $this->success('导入完成', [
            'imported' => $importedCount,
            'updated' => $updatedCount,
            'skipped' => $skippedCount,
            'failed' => $failedCount,
            'errors' => $errorMessages,
            'total_rows' => $highestRow - 1, // 总行数（减去表头）
            'processed_rows' => $importedCount + $updatedCount + $skippedCount + $failedCount, // 处理的行数
            'batch_size' => 'all', // 一次性插入所有数据
            'performance' => [
                'total_time' => microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'],
                'rows_per_second' => ($importedCount + $updatedCount) / max(1, microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'])
            ]
        ]);
    }

    //增加团队成员
    public function addTeamMember()
    {
        $customerIds = $this->request->post('customerIds');
        $userIds = $this->request->post('userIds');
        $customerIds = explode(',', $customerIds);
        $userIds = explode(',', $userIds);
        $permission = $this->request->post('permission', 'read');

        // 权限类型转换
        $type = $permission === 'edit' ? 2 : 1;

        if (empty($customerIds) || empty($userIds)) {
            $this->error('客户和成员不能为空');
        }

        $rows = [];
        foreach ($customerIds as $customerId) {
            foreach ($userIds as $userId) {
                // 检查是否已存在，避免重复添加
                $exists = Db::name('customer_team')
                    ->where(['customer_id' => $customerId, 'staff_id' => $userId])
                    ->find();
                if (!$exists) {
                    $rows[] = [
                        'customer_id' => $customerId,
                        'staff_id' => $userId,
                        'type' => $type
                    ];
                }
            }
        }


        if (empty($rows)) {
            $this->error('所选成员已全部存在于团队，无需重复添加');
        }

        $result = Db::name('customer_team')->insertAll($rows);
        if ($result) {
            $this->success('添加团队成员成功');
        } else {
            $this->error('添加失败');
        }


    }

    // 移除团队成员
    public function removeTeamMember()
    {
        $customerIds = $this->request->post('customerIds');
        $userIds = $this->request->post('userIds');

        // 兼容前端传数组或逗号分隔字符串
        if (is_string($customerIds)) {
            $customerIds = explode(',', $customerIds);
        }
        if (is_string($userIds)) {
            $userIds = explode(',', $userIds);
        }

        if (empty($customerIds) || empty($userIds)) {
            $this->error('数据不能为空');
        }

        foreach ($customerIds as $customerId) {
            foreach ($userIds as $userId) {
                Db::name('customer_team')
                    ->where(['customer_id' => $customerId, 'staff_id' => $userId])
                    ->delete();
            }
        }


        $this->success('移除团队成员成功');

    }

    public function transferToPublic()
    {

        $ids = $this->request->post('ids', '');
        $ids = explode(',', $ids);
        $customer = new \app\common\model\Customer();
        $customer->whereIn('id', $ids)->update(['is_claim' => 0, 'claimtime' => time()]);
        $this->success();
    }

    // 批量转移客户负责人和团队成员
    public function batchTransfer()
    {
        $customerIds = $this->request->post('customerIds');
        $managerId = $this->request->post('managerId');
        $teamIds = $this->request->post('teamIds', '');

        if (is_string($customerIds)) {
            $customerIds = explode(',', $customerIds);
        }
        if (is_string($teamIds) && $teamIds !== '') {
            $teamIds = explode(',', $teamIds);
        } else {
            $teamIds = [];
        }

        if (empty($customerIds) || empty($managerId)) {
            $this->error('客户和负责人不能为空');
        }

        // 1. 批量更新客户表的负责人
        Db::name('customer')
            ->whereIn('id', $customerIds)
            ->where('staff_id', 'neq', $managerId)
            ->update(['staff_id' => $managerId,'recieveDate' => date('Y-m-d H:i:s')]);




        // 2. 批量更新团队成员（可选，先清空再加新团队成员）
        if (!empty($teamIds)) {
            foreach ($customerIds as $customerId) {
                // 先删除原有团队成员
                Db::name('customer_team')->where('customer_id', $customerId)->delete();
                // 再批量插入新团队成员
                $rows = [];
                foreach ($teamIds as $userId) {
                    $rows[] = [
                        'customer_id' => $customerId,
                        'staff_id' => $userId,
                        'type' => 2 // 默认读写
                    ];
                }
                if ($rows) {
                    Db::name('customer_team')->insertAll($rows);
                }
            }
        }

        // 记录操作日志
        $managerName = Db::name('user')->where('id', $managerId)->value('name');
        $teamNames = [];
        if (!empty($teamIds)) {
            $teamNames = Db::name('user')->whereIn('id', $teamIds)->column('name');
        }
        $logResponsible = "将负责人修改为：" . ($managerName ?: $managerId);
        $logTeam = null;
        if (!empty($teamIds)) {
            $teamNamesStr = implode(',', array_filter($teamNames));
            $logTeam = "更新团队成员：" . $teamNamesStr;
        }
        foreach ($customerIds as $customerId) {
            $this->recordOperationLog($customerId, $logResponsible);
            // if ($logTeam !== null) {
            //     $this->recordOperationLog($customerId, $logTeam);
            // }
        }

        $this->success('批量转移成功');

    }

    public function importlog()
    {
        // 获取分页参数
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);

        // 查询条件
        $where = [];
        $userId = $this->auth->id;
        $where['type'] = 1;
        $where['user_id'] = $userId;

        $importlog = new \app\common\model\Importlog();
        $total = $importlog->where($where)->count();
        $list = $importlog
            ->with(['user' => function ($query) {
                $query->field('id,name');
            }])
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select();

        $request = \think\Request::instance();
        $domain = $request->domain();
        foreach ($list as $k => $v) {
            $list[$k]['url'] = $domain . $v['url'];
        }
        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }


    public function exportExcel()
    {
        $fields = $this->request->post('fields'); // 选中的字段
        $selectedIds = $this->request->post('ids', []); // 选中的ID列表
        // 如果没有选择字段，返回错误
        if (empty($fields)) {
            $this->error('请选择要导出的字段');
        }
        $fields = explode(',', $fields);


        $list = Db::name('customer c')
                    ->join('fa_user s', 'c.staff_id = s.id', 'left')
                    ->field('c.*, s.name as staff_name')
                    ->whereIn('c.id', $selectedIds)
                    ->order('c.id', 'desc')
                    ->select();

   
        // 创建新的 Spreadsheet 对象
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 字段映射表
        $fieldMap = [
            'customerName' => '客户名称',
            'productName' => '产品名称/类别',
            'uidipin' => 'UID/PIN',
            'batch' => '批次',
            'orderNo' => '订单号码',
            'orgName' => '机构名称',
            'guaranteeCompany' => '担保公司',
            'phone' => '电话号码',
            'phone1' => '电话号码1',
            'emergencyPhone' => '紧急联系人/其他联系人电话',
            'idCard' => '身份证件号码',
            'homeAddress' => '家庭地址',
            'communicationStatus' => '沟通状态',
            'lawsuitStatus' => '起诉状态',
            'deptId' => '归属部门',
            'backendAmount' => '后台金额',
            'loanAmount' => '借款金额/本金',
            'repaidInterest' => '已还利息',
            'remainingPrincipal' => '剩余本金',
            'remainingPenalty' => '剩余罚息',
            'compensationDate' => '代偿日期',
            'plaintiff' => '原告主体',
            'filingTime' => '立案时间',
            'mailNo' => '邮寄单号',
            'mailDate' => '邮寄日期',
            'paymentDate' => '缴费时间',
            'judgeName' => '法官姓名',
            'judgePhone' => '法官电话',
            'filingCaseNo' => '立案案号',
            'courtTime' => '开庭时间',
            'verdictResult' => '调解/判决结果',
            'executionCaseNo' => '执行案号',
            'executionTime' => '执行时间',
            'remark' => '备注信息',
            'certificate' => '立案凭证',
            'lastfollowtime' => '最后跟进日期',
            'createtime' => '创建时间',
            'updatetime' => '更新时间'
        ];

        // 写入表头
        $col = 1;
        foreach ($fields as $field) {
            if (isset($fieldMap[$field])) {
                $sheet->setCellValueByColumnAndRow($col, 1, $fieldMap[$field]);
                $col++;
            }
        }
        
        // 写入数据
        $row = 2;
        foreach ($list as $item) {
            $col = 1;
            foreach ($fields as $field) {
                if (isset($fieldMap[$field])) {
                    $value = isset($item[$field]) ? $item[$field] : '';

                    // 处理特殊字段
                    switch ($field) {
                        case 'createtime':
                        case 'updatetime':
                            $value = $value ? date('Y-m-d H:i:s', strtotime($value)) : '';
                            break;
                        case 'communicationStatus':
                        case 'lawsuitStatus':
                            $value = is_string($value) ? $value : json_encode($value, JSON_UNESCAPED_UNICODE);
                            break;
                        case 'certificate':
                            // 处理回款信息截图字段，插入图片到单元格，横向排列
                            $request = Request::instance();
                            $domain = $request->domain();
                            $cellCoordinate = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col) . $row;
                            if (!empty($value) && is_string($value)) {
                                $images = json_decode($value, true);
                                if (is_array($images)) {
                                    $imgOffsetX = 0;
                                    foreach ($images as $imgPath) {
                                        if (strpos($imgPath, 'http') === 0) {
                                            $imgUrl = $imgPath;
                                        } else {
                                            $imgUrl = $domain . $imgPath;
                                        }
                                        $localPath = str_replace($domain, '', $imgUrl);
                                        $localPath = ROOT_PATH . 'public' . str_replace('/', DS, $localPath);
                                        if (is_file($localPath)) {
                                            $drawing = new Drawing();
                                            $drawing->setPath($localPath);
                                            $drawing->setHeight(20);
                                            $drawing->setWidth(20);
                                            $drawing->setCoordinates($cellCoordinate);
                                            $drawing->setOffsetX($imgOffsetX);
                                            $drawing->setOffsetY(0);
                                            $drawing->setWorksheet($sheet);
                                            $imgOffsetX += 10; // 横向排列，图片之间有间隔
                                        }
                                    }
                                    $value = '';
                                }
                            }
                            break;
                    }

                    $sheet->setCellValueByColumnAndRow($col, $row, $value);
                    $col++;
                }
            }
            $row++;
        }

        // 设置列宽
        for ($i = 1; $i <= count($fields); $i++) {
            $sheet->getColumnDimensionByColumn($i)->setWidth(15);
        }

        // 设置表头样式
        $headerStyle = [
            'font' => ['bold' => true],
            'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER],
            'borders' => [
                'allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]
            ],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'startColor' => ['rgb' => 'E0E0E0']
            ]
        ];
        $sheet->getStyle('A1:' . $sheet->getHighestColumn() . '1')->applyFromArray($headerStyle);

        // 设置数据区域样式
        $dataStyle = [
            'borders' => [
                'allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]
            ],
            'alignment' => ['vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER]
        ];
        $sheet->getStyle('A2:' . $sheet->getHighestColumn() . ($row - 1))->applyFromArray($dataStyle);

        // 生成文件名
        $filename = '客户数据_' . date('YmdHis') . '.xlsx';

        // 确保目录存在
        $savePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel';
        if (!is_dir($savePath)) {
            mkdir($savePath, 0755, true);
        }

        // 完整的文件保存路径
        $filePath = $savePath . DS . $filename;

        // 保存文件
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save($filePath);

        // 返回文件URL给前端
        $request = \think\Request::instance();
        $domain = $request->domain();
        $fileUrl = $domain . '/uploads/excel/' . $filename;
        $this->success('导出成功', ['url' => $fileUrl]);
    }

    /**
     * 处理导出功能
     * @param array $where 查询条件
     * @param array $params 请求参数
     * @return \think\response\Json
     */
    private function handleExport($where, $params)
    {
        // 获取导出参数
        $export_type = $this->request->post('export_type', 'all'); // 导出类型：selected, currentPage, all
        $fields = $this->request->post('fields'); // 选中的字段
        $selectedIds = $this->request->post('ids', []); // 选中的ID列表

        // 如果没有选择字段，返回错误
        if (empty($fields)) {
            $this->error('请选择要导出的字段');
        }
        $fields = explode(',', $fields);

        // 根据导出类型构建查询
        switch ($export_type) {
            case 'selected':
                if (empty($selectedIds)) {
                    $this->error('请选择要导出的数据');
                }
                $list = Db::name('customer c')
                    ->join('fa_user s', 'c.staff_id = s.id', 'left')
                    ->field('c.*, s.name as staff_name')
                    ->where($where)
                    ->whereIn('c.id', $selectedIds)
                    ->order('c.id', 'desc')
                    ->select();
                break;
            case 'currentPage':
                $list = Db::name('customer c')
                    ->join('fa_user s', 'c.staff_id = s.id', 'left')
                    ->field('c.*, s.name as staff_name')
                    ->where($where)
                    ->whereIn('c.id', $selectedIds)
                    ->order('c.id', 'desc')
                    ->select();
                break;
            case 'all':
            default:
                $list = Db::name('customer c')
                    ->join('fa_user s', 'c.staff_id = s.id', 'left')
                    ->field('c.*, s.name as staff_name')
                    ->where($where)
                    ->order('c.id', 'desc')
                    ->select();
                break;
        }

        // 创建新的 Spreadsheet 对象
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 字段映射表
        $fieldMap = [
            'customerName' => '客户名称',
            'productName' => '产品名称/类别',
            'uidipin' => 'UID/PIN',
            'batch' => '批次',
            'orderNo' => '订单号码',
            'orgName' => '机构名称',
            'guaranteeCompany' => '担保公司',
            'phone' => '电话号码',
            'phone1' => '电话号码1',
            'emergencyPhone' => '紧急联系人/其他联系人电话',
            'idCard' => '身份证件号码',
            'homeAddress' => '家庭地址',
            'communicationStatus' => '沟通状态',
            'lawsuitStatus' => '起诉状态',
            'deptId' => '归属部门',
            'backendAmount' => '后台金额',
            'loanAmount' => '借款金额/本金',
            'repaidInterest' => '已还利息',
            'remainingPrincipal' => '剩余本金',
            'remainingPenalty' => '剩余罚息',
            'compensationDate' => '代偿日期',
            'plaintiff' => '原告主体',
            'filingTime' => '立案时间',
            'mailNo' => '邮寄单号',
            'mailDate' => '邮寄日期',
            'paymentDate' => '缴费时间',
            'judgeName' => '法官姓名',
            'judgePhone' => '法官电话',
            'filingCaseNo' => '立案案号',
            'courtTime' => '开庭时间',
            'verdictResult' => '调解/判决结果',
            'executionCaseNo' => '执行案号',
            'executionTime' => '执行时间',
            'remark' => '备注信息',
            'certificate' => '立案凭证',
            'lastfollowtime' => '最后跟进日期',
            'createtime' => '创建时间',
            'updatetime' => '更新时间'
        ];

        // 写入表头
        $col = 1;
        foreach ($fields as $field) {
            if (isset($fieldMap[$field])) {
                $sheet->setCellValueByColumnAndRow($col, 1, $fieldMap[$field]);
                $col++;
            }
        }
        
        // 写入数据
        $row = 2;
        foreach ($list as $item) {
            $col = 1;
            foreach ($fields as $field) {
                if (isset($fieldMap[$field])) {
                    $value = isset($item[$field]) ? $item[$field] : '';

                    // 处理特殊字段
                    switch ($field) {
                        case 'createtime':
                        case 'updatetime':
                            $value = $value ? date('Y-m-d H:i:s', strtotime($value)) : '';
                            break;
                        case 'communicationStatus':
                        case 'lawsuitStatus':
                            $value = is_string($value) ? $value : json_encode($value, JSON_UNESCAPED_UNICODE);
                            break;
                        case 'certificate':
                            // 处理回款信息截图字段，插入图片到单元格，横向排列
                            $request = Request::instance();
                            $domain = $request->domain();
                            $cellCoordinate = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col) . $row;
                            if (!empty($value) && is_string($value)) {
                                $images = json_decode($value, true);
                                if (is_array($images)) {
                                    $imgOffsetX = 0;
                                    foreach ($images as $imgPath) {
                                        if (strpos($imgPath, 'http') === 0) {
                                            $imgUrl = $imgPath;
                                        } else {
                                            $imgUrl = $domain . $imgPath;
                                        }
                                        $localPath = str_replace($domain, '', $imgUrl);
                                        $localPath = ROOT_PATH . 'public' . str_replace('/', DS, $localPath);
                                        if (is_file($localPath)) {
                                            $drawing = new Drawing();
                                            $drawing->setPath($localPath);
                                            $drawing->setHeight(20);
                                            $drawing->setWidth(20);
                                            $drawing->setCoordinates($cellCoordinate);
                                            $drawing->setOffsetX($imgOffsetX);
                                            $drawing->setOffsetY(0);
                                            $drawing->setWorksheet($sheet);
                                            $imgOffsetX += 10; // 横向排列，图片之间有间隔
                                        }
                                    }
                                    $value = '';
                                }
                            }
                            break;
                    }

                    $sheet->setCellValueByColumnAndRow($col, $row, $value);
                    $col++;
                }
            }
            $row++;
        }

        // 设置列宽
        for ($i = 1; $i <= count($fields); $i++) {
            $sheet->getColumnDimensionByColumn($i)->setWidth(15);
        }

        // 设置表头样式
        $headerStyle = [
            'font' => ['bold' => true],
            'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER],
            'borders' => [
                'allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]
            ],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'startColor' => ['rgb' => 'E0E0E0']
            ]
        ];
        $sheet->getStyle('A1:' . $sheet->getHighestColumn() . '1')->applyFromArray($headerStyle);

        // 设置数据区域样式
        $dataStyle = [
            'borders' => [
                'allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]
            ],
            'alignment' => ['vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER]
        ];
        $sheet->getStyle('A2:' . $sheet->getHighestColumn() . ($row - 1))->applyFromArray($dataStyle);

        // 生成文件名
        $filename = '客户数据_' . date('YmdHis') . '.xlsx';

        // 确保目录存在
        $savePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel';
        if (!is_dir($savePath)) {
            mkdir($savePath, 0755, true);
        }

        // 完整的文件保存路径
        $filePath = $savePath . DS . $filename;

        // 保存文件
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save($filePath);

        // 返回文件URL给前端
        $request = \think\Request::instance();
        $domain = $request->domain();
        $fileUrl = $domain . '/uploads/excel/' . $filename;
        $this->success('导出成功', ['url' => $fileUrl]);
    }

    /**
     * 构建查询条件
     * @param array $params 查询参数
     * @param int $type 查询类型
     * @return array
     */
    private function buildWhere($params, $type)
    {
        $where = [];


        //数据权限
        $userPermissionService = new UserPermissionService();
        $staffids=$userPermissionService->getUsersByPermission($this->auth->id);
        $where['c.staff_id']=['in',$staffids];


        $searchKey = isset($params['searchKey']) ? $params['searchKey'] : '';
        if ($searchKey) {
            $where['c.customerName|c.phone|c.uidipin'] = ['like', "%{$searchKey}%"];
        }
        if (isset($params['customerName']) && !empty($params['customerName'])) {
            $where['c.customerName'] =['like', "%{$params['customerName']}%"]; 
        }

        if (isset($params['customerName']) && !empty($params['customerName'])) {
            $where['c.customerName'] =['like', "%{$params['customerName']}%"]; 
        }
        if (isset($params['uids']) && !empty($params['uids'])) {
            $uids=explode(',', $params['uids']);
            $where['c.uidipin'] =['in',$uids];
        }
        if (isset($params['productName']) && !empty($params['productName'])) {
            $where['c.productName'] = ['like', "%{$params['productName']}%"]; 
        }
        if (isset($params['batch']) && !empty($params['batch'])) {
            $where['c.batch'] = ['like', "%{$params['batch']}%"]; 
        }
        if (isset($params['phone']) && !empty($params['phone'])) {
            $where['c.phone'] = ['like', "%{$params['phone']}%"]; 
        }
        if (isset($params['staff_id']) && !empty($params['staff_id'])) {
            $where['c.staff_id'] = $params['staff_id']; 
        }
        if (isset($params['user_id']) && !empty($params['user_id'])) {
            $where['c.user_id'] = $params['user_id']; 
        }
        if (isset($params['status']) && !empty($params['status'])) {
            $where['c.status'] = $params['status']; 
        }


        if (isset($params['lawsuitStatus']) && !empty($params['lawsuitStatus'])) {
            $where['c.lawsuitStatus'] = ['like', "%{$params['lawsuitStatus']}%"]; 
        }
        if (isset($params['lawyer']) && !empty($params['lawyer'])) {
            $where['c.lawyer'] = ['like', "%{$params['lawyer']}%"]; 
            }
        if (isset($params['mailDateStart']) && !empty($params['mailDateEnd'])) {
            $where['c.mailDate'] = ['between', [$params['mailDateStart'], $params['mailDateEnd']]];
        }
        if (isset($params['filingTimeStart']) && !empty($params['filingTimeEnd'])) {
            $where['c.filingTime'] = ['between', [$params['filingTimeStart'], $params['filingTimeEnd']]];
        }
        if (isset($params['filingCaseNo']) && !empty($params['filingCaseNo'])) {
            $where['c.filingCaseNo'] = ['like', "%{$params['filingCaseNo']}%"]; 
        }
        if (isset($params['executionCaseNo']) && !empty($params['executionCaseNo'])) {
            $where['c.executionCaseNo'] = ['like', "%{$params['executionCaseNo']}%"]; 
        }
        if (isset($params['court']) && !empty($params['court'])) {
            $where['c.court'] = ['like', "%{$params['court']}%"]; 
        }
        if (isset($params['courtPhone']) && !empty($params['courtPhone'])) {
            $where['c.courtPhone'] = ['like', "%{$params['courtPhone']}%"]; 
        }
        if (isset($params['homeAddress']) && !empty($params['homeAddress'])) {
            $where['c.homeAddress'] = ['like', "%{$params['homeAddress']}%"]; 
        }
        if (isset($params['createtimeStart']) && !empty($params['createtimeEnd'])) {
            $where['c.createtime'] = ['between', [$params['createtimeStart'], $params['createtimeEnd']]];
        }
        if (isset($params['recieveDateStart']) && !empty($params['recieveDateEnd'])) {
            $where['c.recieveDate'] = ['between', [$params['recieveDateStart'], $params['recieveDateEnd']]];    
        }   

        if (isset($params['communicationStatus']) && !empty($params['communicationStatus'])) {
            $where['c.communicationStatus'] = ['like', "%{$params['communicationStatus']}%"]; 
        }  
        
        if (isset($params['department_id']) && !empty($params['department_id'])) {
            // 获取这些部门的所有用户ID
            $userIds = $this->getDepartmentUserIds($params['department_id']);
            // 与数据权限的staffids取交集
            $where['c.staff_id'] = ['in', array_intersect($userIds, $staffids)];
        } 


        switch ($type) {
            case 1:
                break;
            case 2:
                $where['c.staff_id'] = $this->auth->id;
                break;
            case 3:
                $staffids = Db::name('user')->where('leader_id', $this->auth->id)->column('id');
                $where['c.staff_id'] = ['in', $staffids];
                break;
            case 4:
                $todayStart = strtotime(date('Y-m-d 00:00:00'));
                $todayEnd = strtotime(date('Y-m-d 23:59:59'));
                $where['c.lastfollowtime'] = ['between', [$todayStart, $todayEnd]];
                break;
            case 5:
                $todayStart = date('Y-m-d 00:00:00');
                $todayEnd = date('Y-m-d 23:59:59');
                $where['c.createtime'] = ['between', [$todayStart, $todayEnd]];
                break;
            case 6:
                $where['c.lastfollowtime'] = null;
                break;
            case 7:
                $sevenDaysAgo = strtotime('-7 days');
                $where['c.lastfollowtime'] = ['<', $sevenDaysAgo];
                break;
            default:
                break;
        }
        return $where;
    }

    //获取权限

    /**
     * 批量修改客户信息
     * @return \think\response\Json
     */
    public function modifyCustomer()
    {
        $params = $this->request->post();
        
        // 验证必填参数
        if (empty($params['editField']) || empty($params['editMethod']) || empty($params['ids'])) {
            $this->error('缺少参数');
        }
        
        $editField = $params['editField'];
        $editMethod = $params['editMethod'];
        $ids = $params['ids'];
        
        // 验证字段名是否合法（防止SQL注入）
        $allowedFields = [
            'productName', 'customerName', 'phone', 'uidipin', 'address', 'remark',
            'staff_id', 'user_id', 'progress', 'status', 'communicationStatus',
            'lawsuitStatus', 'lawyer', 'mailDate', 'filingTime', 'filingCaseNo',
            'executionCaseNo', 'court', 'courtPhone', 'homeAddress', 'recieveDate',
            'batch'  // 添加批次字段支持
        ];
        
        if (!in_array($editField, $allowedFields)) {
            $this->error('不允许修改的字段：' . $editField);
        }
        
        // 验证修改方法
        if (!in_array($editMethod, ['replace', 'append', 'prepend', 'clear'])) {
            $this->error('不支持的修改方法：' . $editMethod);
        }
        
        // 处理ID列表
        if (is_string($ids)) {
            $ids = explode(',', $ids);
        }
        
        if (empty($ids)) {
            $this->error('ID列表不能为空');
        }
        
        // 验证ID格式
        $ids = array_filter(array_map('intval', $ids));
        if (empty($ids)) {
            $this->error('ID格式不正确');
        }
        
        // 获取新值（clear方法不需要新值）
        $newValue = null;
        if ($editMethod !== 'clear') {
            $newValue = $params[$editField] ?? null;
            if ($newValue === null) {
                $this->error('缺少新值参数：' . $editField);
            }
        }
        
        // 根据修改方法确定更新值
        $updateValue = ($editMethod === 'clear') ? '' : $newValue;
        
        // 批量更新（replace和clear方法）
        $result = Db::name('customer')
            ->where('id', 'in', $ids)
            ->update([
                $editField => $updateValue,
                'updatetime' => time()
            ]);
        
        if ($result !== false) {
            // 记录操作日志（按客户逐条记录）
            $fieldLabelMap = [
                'productName' => '产品名称',
                'batch' => '批次',
            ];
            $fieldName = isset($fieldLabelMap[$editField]) ? $fieldLabelMap[$editField] : $editField;
            if ($editMethod === 'clear') {
                $logContent = "将{$fieldName}清空";
            } else {
                $displayValue = is_array($newValue) ? json_encode($newValue, JSON_UNESCAPED_UNICODE) : (string)$newValue;
                $logContent = "将{$fieldName}修改为：{$displayValue}";
            }
            foreach ($ids as $cid) {
                $this->recordOperationLog($cid, $logContent);
            }
            $this->success("批量修改成功，共修改 {$result} 条记录", [
                'updated_count' => $result,
                'total_ids' => count($ids),
                'field' => $editField,
                'method' => $editMethod,
                'new_value' => $editMethod === 'clear' ? '(已清空)' : $newValue
            ]);
        } else {
            $this->error('没有记录被修改');
        }
    }

}